import {Component} from '@angular/core';
import {IonicPage, NavController, NavParams, ToastController} from 'ionic-angular';
import {
  Http,
  Headers,
  RequestOptions,
  URLSearchParams
} from '@angular/http';
import {LoginPage} from '../login/login';
import {AppConfig} from '../../app/app.config';
import {Md5} from "ts-md5/dist/md5";
import {baseCommon} from '../../common/baseCommon';
import {Storage} from '@ionic/storage'

/**
 * Generated class for the Register2Page page.
 *
 * See https://ionicframework.com/docs/components/#navigation for more info on
 * Ionic pages and navigation.
 */

@IonicPage()
@Component({
  selector: 'page-register2',
  templateUrl: 'register2.html',
})
export class Register2Page{

  code: any;
  password: any;
  passwordAgain: any;
  getPhone: any;
  version: any;

  constructor(public navCtrl: NavController, public navParams: NavParams, public http: Http,
              public toastCtrl: ToastController,
              public storage: Storage) {
    this.getPhone = navParams.data.phone;
    console.log(this.getPhone);
  }

  ionViewDidLoad() {

    this.storage.get('version').then(val => {
      if (val == null) {
        this.storage.set('version', 1)
        this.version = 1;
      } else {
        this.version = val;
      }
    })
  }

  /**
   * 回到登录页面
   */
  back() {
    this.navCtrl.push(LoginPage)
  }

  /**
   * 注册
   */
  register() {
    if(this.code == ''){
      baseCommon.showToast(this.toastCtrl,'请输入验证码..');
    }else if(this.password == ''){
      baseCommon.showToast(this.toastCtrl,'请输入密码..');
    }else if(this.password != this.passwordAgain){
      baseCommon.showToast(this.toastCtrl, "两次输入的密码不一致！");
    }else if(this.password == this.passwordAgain) {
      this.Register(AppConfig.httpLoc + '/register/check', this.code, this.password, this.getPhone);
    } else{
      baseCommon.showToast(this.toastCtrl, "本程序猿也不知道发生了什么错误..");
    }
  }

  /**
   * 注册
   *
   * @param {any} apiUrl
   * @param {any} code
   * @param {any} password
   * @param {any} phone
   * @memberof Register2Page
   */
  Register(apiUrl, code, password, phone) {

    let headers = new Headers({
      'Content-Type': 'application/x-www-form-urlencoded'
    });

    let options = new RequestOptions({
      headers: headers
    });

    let pramas: URLSearchParams = new URLSearchParams();

    pramas.set('code', code);
    pramas.set('password', Md5.hashStr(password).toString());
    pramas.set('phone', phone);

    let getData: any;

    this.http.post(apiUrl, pramas, options)
      .toPromise()
      .then(data => {
        // loading.dismiss();
        getData = data.json();
        if (getData.message == "成功") {
          // this.init(this.storage);
          baseCommon.showToast(this.toastCtrl, '注册成功:)');
          this.navCtrl.push(LoginPage);
        } else {
          // super.showToast(this.toastCtrl,"手机号或者密码输入错误！")
        }
      }, err => {
        console.log(err);
      })
  }

}
